<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. @Resource–手动注入使用Field注入（用于注解方式）,注入依赖对象可以采用手工装配或自动装配.在实际应用中建议使用手工装配，因为自动装配会产生未知情况，开发人员无法预见最终的装配结果。@Resource注解和@Autowired一样，同样也可以标注在字段或属性的setter方法上，但它默认按名称装配。名称可以通过@Resource的name属性指定，如果没有指定name属性">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaEE-Spring-IoC注解">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring-IoC注解/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. @Resource–手动注入使用Field注入（用于注解方式）,注入依赖对象可以采用手工装配或自动装配.在实际应用中建议使用手工装配，因为自动装配会产生未知情况，开发人员无法预见最终的装配结果。@Resource注解和@Autowired一样，同样也可以标注在字段或属性的setter方法上，但它默认按名称装配。名称可以通过@Resource的name属性指定，如果没有指定name属性">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ab13c953af8ef192.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-21c86d54c0b200a5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-afe51c70e08acebe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-d37e66e0e76459a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-99321bad04c118da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-7ea690a8faf14943.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2dd57bf68f6ef5a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-4fed7921a6e5f5a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-9db2e387197f6ea3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:51:49.609Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaEE-Spring-IoC注解">
<meta name="twitter:description" content="####1. @Resource–手动注入使用Field注入（用于注解方式）,注入依赖对象可以采用手工装配或自动装配.在实际应用中建议使用手工装配，因为自动装配会产生未知情况，开发人员无法预见最终的装配结果。@Resource注解和@Autowired一样，同样也可以标注在字段或属性的setter方法上，但它默认按名称装配。名称可以通过@Resource的name属性指定，如果没有指定name属性">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-ab13c953af8ef192.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring-IoC注解/"/>





  <title>JavaEE-Spring-IoC注解 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring-IoC注解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaEE-Spring-IoC注解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. @Resource–手动注入<br>使用Field注入（用于注解方式）,注入依赖对象可以采用手工装配或自动装配.在实际应用中建议使用手工装配，因为自动装配会产生未知情况，开发人员无法预见最终的装配结果。<br>@Resource注解和@Autowired一样，同样也可以标注在字段或属性的setter方法上，但它默认按名称装配。名称可以通过@Resource的name属性指定，如果没有指定name属性，当注解标注在字段上时，即默认取字段的名称作为bean名称寻找依赖对象，当注解标注在属性的setter方法上时，即默认取属性名作为bean名称寻找依赖对象。<br><a id="more"></a></p>
<p><strong>注意：如果没有指定name属性，并且按照默认的名称仍然找不到依赖对象时， @Resource注解会回退到按类型装配。但一旦指定了name属性，就只能按名称装配了。 </strong><br>1). 创建项目并导包<br>导入Jar包：spring-beans-5.0.5.RELEASE.jar、spring-context-5.0.5.RELEASE.jar、spring-core-5.0.5.RELEASE.jar、spring-expression-5.0.5.RELEASE.jar、spring-aop-5.0.5.RELEASE.jar、<a href="http://commons.apache.org/proper/commons-logging/" target="_blank" rel="noopener">commons-logging-1.2.jar</a>.(注：这里多了aop的jar包)<br><img src="https://upload-images.jianshu.io/upload_images/3110861-ab13c953af8ef192.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>2). 在src目录下创建bean.xml文件，并向beans节点中添加<code>&lt;context:annotation-config/&gt;</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 在java代码中使用@Autowired或@Resource注解方式进行装配。</span><br><span class="line">		@Autowired默认按类型装配，@Resource默认按名称装配，当找不到与名称匹配的bean才会按类型装配</span><br><span class="line">		这个配置隐式注册了多个对注解进行解析处理的处理器：</span><br><span class="line">		AutowiredAnnotationBeanPostProcessor</span><br><span class="line">		CommonAnnotationBeanPostProcessor</span><br><span class="line">		PersistenceAnnotationBeanPostProcessor</span><br><span class="line">		RequiredAnnotationBeanPostProcessor </span><br><span class="line">	--&gt;</span><br><span class="line">    &lt;context:annotation-config/&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>3).  在src目录下新建com.mazaiting.dao包，然后创建PersonDao接口<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface PersonDao &#123;</span><br><span class="line">	void add();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>4). 创建com.mazaiting.dao.impl包，并创建实现PersonDao接口的PersonDaoImpl 实现类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class PersonDaoImpl implements PersonDao &#123;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public void add() &#123;</span><br><span class="line">		System.out.println(&quot;执行PersonDaoImpl中的add()方法&quot;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>5). 创建com.mazaiting.service类，并创建PersonService接口<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface PersonService &#123;</span><br><span class="line">	void save();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>6). 创建com.mazaiting.service.impl,并创建实现PersonService接口的PersonServiceImpl实现类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">	private PersonDao personDao;</span><br><span class="line">	private String name;</span><br><span class="line">	</span><br><span class="line">	public PersonServiceImpl() &#123;&#125;</span><br><span class="line">	public PersonServiceImpl(PersonDao personDao, String name) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">		this.name = name;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		System.out.println(&quot;PersonServiceImpl--&quot; + name);</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>7). 在bean.xml文件中添加配置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 在java代码中使用@Autowired或@Resource注解方式进行装配。</span><br><span class="line">		@Autowired默认按类型装配，@Resource默认按名称装配，当找不到与名称匹配的bean才会按类型装配</span><br><span class="line">		这个配置隐式注册了多个对注解进行解析处理的处理器：</span><br><span class="line">		AutowiredAnnotationBeanPostProcessor</span><br><span class="line">		CommonAnnotationBeanPostProcessor</span><br><span class="line">		PersistenceAnnotationBeanPostProcessor</span><br><span class="line">		RequiredAnnotationBeanPostProcessor </span><br><span class="line">	--&gt;</span><br><span class="line">    &lt;context:annotation-config/&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;bean id=&quot;personDao&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;bean id=&quot;personService&quot; class=&quot;com.mazaiting.service.impl.PersonServiceImpl&quot;&gt;&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>8). 在PersonServiceImpl中添加注解<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">	@Resource private PersonDao personDao;</span><br><span class="line">	private String name;</span><br><span class="line">	</span><br><span class="line">	public PersonServiceImpl() &#123;&#125;</span><br><span class="line">	public PersonServiceImpl(PersonDao personDao, String name) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">		this.name = name;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>9). 创建测试文件TestSpring<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class TestSpring &#123;</span><br><span class="line"></span><br><span class="line">	@Test</span><br><span class="line">	public void test() &#123;</span><br><span class="line">		// 加载配置文件</span><br><span class="line">		ApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);</span><br><span class="line">		// 创建对象</span><br><span class="line">		PersonService service = (PersonService) context.getBean(&quot;personService&quot;);</span><br><span class="line">		// 执行方法</span><br><span class="line">		service.save();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>10). 打印结果<br><img src="https://upload-images.jianshu.io/upload_images/3110861-21c86d54c0b200a5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>11). 将bean.xml文件中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;personDao&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;personDaoTest&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>然后执行测试代码，打印结果为：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-afe51c70e08acebe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>12). 修改PersonServiceImpl文件为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">//  1. 注解在变量上</span><br><span class="line">//	@Resource private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	// 2. 注解在set方法上</span><br><span class="line">	private PersonDao personDao;</span><br><span class="line">	@Resource</span><br><span class="line">	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	private String name;</span><br><span class="line">	</span><br><span class="line">	public PersonServiceImpl() &#123;&#125;</span><br><span class="line">	public PersonServiceImpl(PersonDao personDao, String name) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">		this.name = name;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>执行结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-d37e66e0e76459a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>####2. @Autowire注解完成属性装配<br>1). 将PersonServiceImpl内容修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">//  1. 注解在变量上</span><br><span class="line">//	@Resource private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">//	// 2. 注解在set方法上</span><br><span class="line">//	private PersonDao personDao;</span><br><span class="line">//	@Resource</span><br><span class="line">//	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">//		this.personDao = personDao;</span><br><span class="line">//	&#125;</span><br><span class="line">	</span><br><span class="line">	// 3. @Autowire注解</span><br><span class="line">	@Autowired private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>运行测试代码结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-99321bad04c118da.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<p>#####注意：@Autowired注解是按类型装配依赖对象，默认情况下它要求依赖对象必须存在，如果允许null值，可以设置它的required属性为false。如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@Autowired(required=true) @Qualifier(&quot;personDaoxxxx&quot;) private PersonDao personDao;  </span><br><span class="line">`</span><br></pre></td></tr></table></figure></p>
<p>required=true代表字段personDao必须要注入值，也即是说在Spring容器中根据类型找不到对应的bean，那就会报异常；required=false意味着在Spring容器中根据类型找不到对应的的bean，就会把该字段设为null。</p>
<p>2). 与@Qualifier结合使用<br>将PersonServiceImpl中的代码修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">//  1. 注解在变量上</span><br><span class="line">//	@Resource private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">//	// 2. 注解在set方法上</span><br><span class="line">//	private PersonDao personDao;</span><br><span class="line">//	@Resource</span><br><span class="line">//	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">//		this.personDao = personDao;</span><br><span class="line">//	&#125;</span><br><span class="line">	</span><br><span class="line">	// 3. @Autowire注解</span><br><span class="line">	@Autowired @Qualifier(&quot;personDaoTest&quot;) private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>执行测试代码结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-7ea690a8faf14943.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>####3. 依赖注入——自动装配依赖对象<br>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;...&quot; class=&quot;...&quot; autowire=&quot;byType&quot;/&gt;</span><br></pre></td></tr></table></figure></p>
<p>autowire属性取值如下：</p>
<ul>
<li>byType：按类型装配，可以根据属性的类型，在容器中寻找跟该类型匹配的bean。如果发现多个，那么将会抛出异常。如果没有找到，即属性值为null。</li>
<li>byName：按名称装配，可以根据属性的名称，在容器中寻找跟该属性名相同的bean，如果没有找到，即属性值为null。</li>
<li>constructor与byType的方式类似，不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean，那么将会抛出异常。</li>
<li>autodetect：通过bean类的自省机制（introspection）来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器，那么将使用byType方式。</li>
</ul>
<p>1). 将PersonServiceImpl代码修改<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">//  1. 注解在变量上</span><br><span class="line">//	@Resource private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">//	// 2. 注解在set方法上</span><br><span class="line">//	private PersonDao personDao;</span><br><span class="line">//	@Resource</span><br><span class="line">//	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">//		this.personDao = personDao;</span><br><span class="line">//	&#125;</span><br><span class="line">	</span><br><span class="line">	// 3. @Autowire注解</span><br><span class="line">//	@Autowired @Qualifier(&quot;personDaoTest&quot;) private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	// 4. 自动装配</span><br><span class="line">	private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>2). 修改bean.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 在java代码中使用@Autowired或@Resource注解方式进行装配。</span><br><span class="line">		@Autowired默认按类型装配，@Resource默认按名称装配，当找不到与名称匹配的bean才会按类型装配</span><br><span class="line">		这个配置隐式注册了多个对注解进行解析处理的处理器：</span><br><span class="line">		AutowiredAnnotationBeanPostProcessor</span><br><span class="line">		CommonAnnotationBeanPostProcessor</span><br><span class="line">		PersistenceAnnotationBeanPostProcessor</span><br><span class="line">		RequiredAnnotationBeanPostProcessor </span><br><span class="line">	--&gt;</span><br><span class="line">    &lt;context:annotation-config/&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;bean id=&quot;personDaoTest&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;!-- &lt;bean id=&quot;personService&quot; class=&quot;com.mazaiting.service.impl.PersonServiceImpl&quot;&gt;&lt;/bean&gt; --&gt;</span><br><span class="line">	&lt;bean id=&quot;personService&quot; class=&quot;com.mazaiting.service.impl.PersonServiceImpl&quot; autowire=&quot;byType&quot;&gt;&lt;/bean&gt;	</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>运行测试代码打印：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2dd57bf68f6ef5a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>3). 若将bean.xml文件改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 在java代码中使用@Autowired或@Resource注解方式进行装配。</span><br><span class="line">		@Autowired默认按类型装配，@Resource默认按名称装配，当找不到与名称匹配的bean才会按类型装配</span><br><span class="line">		这个配置隐式注册了多个对注解进行解析处理的处理器：</span><br><span class="line">		AutowiredAnnotationBeanPostProcessor</span><br><span class="line">		CommonAnnotationBeanPostProcessor</span><br><span class="line">		PersistenceAnnotationBeanPostProcessor</span><br><span class="line">		RequiredAnnotationBeanPostProcessor </span><br><span class="line">	--&gt;</span><br><span class="line">    &lt;context:annotation-config/&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;bean id=&quot;personDaoTest&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;!-- &lt;bean id=&quot;personService&quot; class=&quot;com.mazaiting.service.impl.PersonServiceImpl&quot;&gt;&lt;/bean&gt; --&gt;</span><br><span class="line">	&lt;bean id=&quot;personService&quot; class=&quot;com.mazaiting.service.impl.PersonServiceImpl&quot; autowire=&quot;byName&quot;&gt;&lt;/bean&gt;	</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>则必须将其中的<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;personDaoTest&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;personDao&quot; class=&quot;com.mazaiting.dao.impl.PersonDaoImpl&quot;&gt;&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>执行测试代码：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-4fed7921a6e5f5a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p>####4. Spring自动扫描和管理Bean<br>1). 使用XML的bean定义来配置组件时，在一个稍大的项目中，通常会有上百个组件，如果这些组件采用XML的bean定义来配置，显然会增加配置文件的体积，查找及维护起来也不太方便。Spring2.5为我们引入了组件自动扫描机制，它可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类，并把这些类纳入进Spring容器中管理。它的作用和在XML文件中使用bean节点配置组件是一样的。要使用自动扫描机制，我们需要打开以下配置信息：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;context:component-scan base-package=&quot;com.mazaiting&quot; /&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>其中&lt;context:component-scan base-package=”com.mazaiting” /&gt;这个配置隐式注册了多个对注解进行解析处理的处理器，包括<a href="context:annotation-config/" target="_blank" rel="noopener">context:annotation-config/</a>该配置注册的处理器，也就是说写了&lt;context:component-scan base-package=”com.mazaiting” /&gt;配置，就不用写<a href="context:annotation-config/" target="_blank" rel="noopener">context:annotation-config/</a>配置了，此外base-package为需要扫描的包(含子包)。<br>@Service用于标注业务层组件、 @Controller用于标注控制层组件（如Struts2中的action）、@Repository用于标注数据访问组件，即DAO组件。而@Component泛指组件，当组件不好归类的时候，我们可以使用这个注解进行标注。<br>2). 修改bean.xml文件为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans</span><br><span class="line">        http://www.springframework.org/schema/beans/spring-beans.xsd</span><br><span class="line">        http://www.springframework.org/schema/context</span><br><span class="line">        http://www.springframework.org/schema/context/spring-context-4.2.xsd&quot;&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 自动扫描和管理Bean配置 --&gt;</span><br><span class="line">	&lt;context:component-scan base-package=&quot;com.mazaiting&quot;/&gt;	</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>3). 修改PersonServiceImpl和PersonDaoImpl类内容<br><strong>PersonServiceImpl.java</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Service</span><br><span class="line">public class PersonServiceImpl implements PersonService &#123;</span><br><span class="line">	private PersonDao personDao;</span><br><span class="line">	</span><br><span class="line">	public void setPersonDao(PersonDao personDao) &#123;</span><br><span class="line">		this.personDao = personDao;</span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void save() &#123;</span><br><span class="line">		personDao.add();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>PersonDaoImpl.java</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Repository</span><br><span class="line">public class PersonDaoImpl implements PersonDao &#123;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public void add() &#123;</span><br><span class="line">		System.out.println(&quot;执行PersonDaoImpl中的add()方法&quot;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>4). 修改测试代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class TestSpring &#123;</span><br><span class="line"></span><br><span class="line">	@Test</span><br><span class="line">	public void test() &#123;</span><br><span class="line">		// 加载配置文件</span><br><span class="line">		ApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);</span><br><span class="line">		// 创建对象</span><br><span class="line">		PersonService service = (PersonService) context.getBean(&quot;personServiceImpl&quot;);</span><br><span class="line">		PersonDao dao = (PersonDao) context.getBean(&quot;PersonDaoImpl&quot;);</span><br><span class="line">		System.out.println(service.toString());</span><br><span class="line">		System.out.println(dao.toString());		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">``` </span><br><span class="line">执行测试代码打印结果：</span><br><span class="line">![图9.png](https://upload-images.jianshu.io/upload_images/3110861-0133c1e5ac003fe1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</span><br><span class="line"></span><br><span class="line">5). 如果我们想使用按指定名称获取，可将PersonServiceImpl类的代码修改为：</span><br><span class="line">I. 修改PersonServiceImpl.java文件</span><br></pre></td></tr></table></figure></p>
<p>@Service(“personService”)<br>public class PersonServiceImpl implements PersonService {<br>    private PersonDao personDao;</p>
<pre><code>public void setPersonDao(PersonDao personDao) {
    this.personDao = personDao;
}    

@Override
public void save() {
    personDao.add();
}
</code></pre><p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">II. 修改测试代码如下：</span><br></pre></td></tr></table></figure></p>
<p>public class TestSpring {</p>
<pre><code>@Test
public void test() {
    // 加载配置文件
    ApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);
    // 创建对象
    PersonService service = (PersonService) context.getBean(&quot;personService&quot;);
    PersonDao dao = (PersonDao) context.getBean(&quot;personDaoImpl&quot;);
    System.out.println(service.toString());
    System.out.println(dao.toString());        
}
</code></pre><p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">III. 执行测试代码，打印结果如下：</span><br><span class="line">![图10.png](https://upload-images.jianshu.io/upload_images/3110861-8cfafb2373866269.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</span><br><span class="line"></span><br><span class="line">####5. 管理作用域</span><br><span class="line">默认创建的对象作用域为SingleTon, 我们可以通过@Scope来管理作用域</span><br><span class="line">1). 修改PersonServiceImpl.java文件</span><br></pre></td></tr></table></figure></p>
<p>@Service(“personService”)<br>@Scope(“prototype”)<br>public class PersonServiceImpl implements PersonService {<br>    private PersonDao personDao;</p>
<pre><code>public void setPersonDao(PersonDao personDao) {
    this.personDao = personDao;
}    

@Override
public void save() {
    personDao.add();
}
</code></pre><p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2). 修改测试代码</span><br></pre></td></tr></table></figure></p>
<p>public class TestSpring {</p>
<pre><code>@Test
public void test() {    
    // 加载配置文件
    ApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);
    // 创建对象
    PersonService service1 = (PersonService) context.getBean(&quot;personService&quot;);
    PersonService service2 = (PersonService) context.getBean(&quot;personService&quot;);
    System.out.println(service1 == service2);        
}
</code></pre><p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">执行测试代码，打印结果：</span><br><span class="line">![图11.png](https://upload-images.jianshu.io/upload_images/3110861-dae5d8ec34dce851.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</span><br><span class="line">#####说明：prototype作用域意味着每次从Spring容器获取bean都是新的对象嘛。</span><br><span class="line">3). 使用@PostConstruct和@PreDestroy来注解初始化方法和销毁当前类方法</span><br><span class="line">修改PersonServiceImpl.java文件为：</span><br></pre></td></tr></table></figure></p>
<p>@Service(“personService”)<br>public class PersonServiceImpl implements PersonService {<br>    private PersonDao personDao;</p>
<pre><code>public void setPersonDao(PersonDao personDao) {
    this.personDao = personDao;
}    

@Override
public void save() {
    personDao.add();
}

@PostConstruct
public void init() {
    System.out.println(&quot;初始化&quot;);
}

@PreDestroy
public void destroy() {
    System.out.println(&quot;销毁&quot;);
}
</code></pre><p>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">修改测试代码为：</span><br></pre></td></tr></table></figure></p>
<p>public class TestSpring {</p>
<pre><code>@Test
public void test() {        
    // 加载配置文件
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);
    // 创建对象
    PersonService service1 = (PersonService) context.getBean(&quot;personService&quot;);
    context.close();
}
</code></pre><p>}<br><code>`</code><br>执行测试代码，打印结果为：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-9db2e387197f6ea3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图12.png"></p>
<p>###<a href="https://download.csdn.net/download/mazaiting/10352097" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring-IoC入门/" rel="next" title="JavaEE-Spring-IoC入门">
                <i class="fa fa-chevron-left"></i> JavaEE-Spring-IoC入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-SpringMVC/" rel="prev" title="JavaEE-SpringMVC">
                JavaEE-SpringMVC <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
